#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File    :   test.py
@Contact :   gaojingyu@lyzdfintech.com

@Modify Time           @Author      @Version      @Desciption
-----------------    ----------    ----------    ------------
2021/4/7 5:59 下午     gaojingyu       1.0           None
"""

import logging
from crontab import CronTab
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from backend.common.api_response import JsonResponse
from backend.common.common import record_dynamic
from backend.models import Sys_DingDing, Project
# from backend.serializers import ProjectSerializer, ProjectDeserializer, \
#     ProjectMemberDeserializer
from backend.serializers import SysDingDingSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。
"""
龙盈智达--钉钉消息配置
"""


class LyzdDingDingList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        """
        获取钉钉消息配置列表
        :param request:
        :return:
        """
        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        name = request.GET.get("name")

        if name:
            obi = Sys_DingDing.objects.filter(name__contains=name).order_by("delete_flag", "-id")

        else:

            obi = Sys_DingDing.objects.all().order_by("delete_flag", "-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        serialize = SysDingDingSerializer(obm, many=True)

        # json_data = serializers.serialize("json", obm, ensure_ascii=False)
        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


class AddDingDing(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):
        """
        验证参数
        :param data:
        :return:
        """
        try:
            # 必传参数 name, version, type
            if not data["name"] or not data["ding_secret"] or not data["ding_url"]:
                return JsonResponse(code="999996", msg="参数有误！")

        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        新增dingding
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        result = self.parameter_check(data)
        if result:
            return result
        data["user"] = request.user.pk
        dingding_serializer = SysDingDingSerializer(data=data)

        try:
            Sys_DingDing.objects.get(name=data["name"])

            return JsonResponse(code="999997", msg="存在相同名称")
        except ObjectDoesNotExist:
            with transaction.atomic():
                if dingding_serializer.is_valid():

                    dingding_serializer.is_valid()
                    # 保持新项目
                    dingding_serializer.save()
                    # 记录动态

                    return JsonResponse(data={
                        "id": dingding_serializer.data.get("id")
                    }, code="999999", msg="成功")
                else:
                    return JsonResponse(code="999998", msg="失败")


class UpdateDingDing(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):
        """
        校验参数
        :param data:
        :return:
        """
        try:
            # 校验project_id类型为int
            if not isinstance(data["id"], int):
                return JsonResponse(code="999996", msg="参数有误！")
            # 必传参数 name, version , type
            if not data["name"] or not data["ding_secret"] or not data["ding_url"]:
                return JsonResponse(code="999996", msg="参数有误！")
            # # type 必为Web， App
            # if data["type"] not in ["Web", "App"]:
            #     return JsonResponse(code="999996", msg="参数有误！")
        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        修改项目
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        print("|||||||||")
        print(data)  # {'id': 6, 'env_name': 'AAAA', 'address': 'BBBBB', 'content': 'CCCCCCC'}

        result = self.parameter_check(data)
        if result:
            return result
        # 查找项目是否存在
        try:
            obj = Sys_DingDing.objects.get(id=data["id"])
            print("}}}}}}}}}}}}")

            print(obj)  # 2131
            if not request.user.is_superuser and obj.user.is_superuser:
                return JsonResponse(code="999983", msg="无操作权限！")
        except ObjectDoesNotExist:
            return JsonResponse(code="999995", msg="项目不存在！")
        # 查找是否相同名称的项目
        dingding_name = Sys_DingDing.objects.filter(name=data["name"]).exclude(id=data["id"])
        if len(dingding_name):
            return JsonResponse(code="999997", msg="存在相同名称")
        else:
            # environment_serializer = SysEnvironmentSerializer(data=data)
            serializer = SysDingDingSerializer(data=data)
            with transaction.atomic():
                if serializer.is_valid():
                    # 修改项目
                    serializer.update(instance=obj, validated_data=data)
                    # 记录动态
                    record_dynamic(project=data["id"],
                                   _type="修改", operationObject="钉钉列表", user=request.user.pk, data=data["name"])
                    return JsonResponse(code="999999", msg="成功")
                else:
                    return JsonResponse(code="999998", msg="失败")


class EditStatusDingDing(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):

        """查询条件"""
        # 必传参数
        data = JSONParser().parse(request)

        print(data)
        print(type(data))
        ding_id = tuple(data.values())[0]

        print(ding_id)
        status = Sys_DingDing.objects.filter(id=ding_id)
        print(status)
        flag = status[0].delete_flag
        print(flag)
        if flag == '0':
            Sys_DingDing.objects.filter(id=ding_id).update(
                delete_flag=1
            )
            return JsonResponse(code="999999", msg="禁用成功")
        elif flag == '1':
            Sys_DingDing.objects.filter(id=ding_id).update(
                delete_flag=0
            )
            return JsonResponse(code="999999", msg="启用成功")


"""
DelDingDing,删除
"""



class DelDingDing(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):
        """
        校验参数
        :param data:
        :return:
        """
        try:
            # 校验project_id类型为int
            if not isinstance(data["ids"], list):
                return JsonResponse(code="999996", msg="参数有误！")
            for i in data["ids"]:
                if not isinstance(i, int):
                    return JsonResponse(code="999996", msg="参数有误！")
        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        删除项目
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        result = self.parameter_check(data)
        if result:
            return result
        try:
            for i in data["ids"]:
                try:
                    obj = Sys_DingDing.objects.get(id=i)
                    if not request.user.is_superuser and obj.user.is_superuser:
                        return JsonResponse(code="999983", msg=str(obj) + "无操作权限！")
                except ObjectDoesNotExist:
                    return JsonResponse(code="999995", msg="项目不存在！")
            for j in data["ids"]:
                obj = Sys_DingDing.objects.filter(id=j)
                obj.delete()
                # my_user_cron = CronTab(user=True)
                # my_user_cron.remove_all(comment=j)
                # my_user_cron.write()
            return JsonResponse(code="999999", msg="成功")
        except ObjectDoesNotExist:
            return JsonResponse(code="999995", msg="项目不存在！")
